<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="系统名称" prop="channelName">
        <el-input
          v-model="queryParams.channelName"
          placeholder="请输入系统名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="系统编号" prop="channelCode">
        <el-input
          v-model="queryParams.channelCode"
          placeholder="请输入系统编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['yjcz:channel:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['yjcz:channel:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['yjcz:channel:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['yjcz:channel:import']"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['yjcz:channel:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="channelList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="系统名称" align="center" prop="channelName" />
      <el-table-column label="系统编号" align="center" prop="channelCode" />
      <el-table-column label="系统负责人" align="center" prop="channelUserName" />
      <el-table-column label="系统所属组别" align="center" prop="channelGroupName" />
      <el-table-column label="人员列表" align="center" >
        <template slot-scope="scope">
          <el-tooltip v-if="null != scope.row.channelUserNames && scope.row.channelUserNames.length > 25" popper-class="my-tooltip" effect="dark" :content="scope.row.channelUserNames" placement="top-start">
            <span>{{scope.row.channelUserNames.substring(0, 25) + '...'}}</span>
          </el-tooltip>
          <span v-else>
            {{scope.row.channelUserNames}}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="channelRemark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['yjcz:channel:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['yjcz:channel:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改应用系统对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="系统名称" prop="channelName">
          <el-input v-model="form.channelName" placeholder="请输入系统名称" />
        </el-form-item>
        <el-form-item label="系统编号" prop="channelCode">
          <el-input v-model="form.channelCode" placeholder="请输入系统编号" />
        </el-form-item>
        <el-form-item label="系统负责人" prop="channelUserId">
          <el-select v-model="form.channelUserId" @change="onUserListChange" filterable placeholder="请选择系统负责人">
            <el-option
              v-for="item in userList"
              :key="item.userId"
              :label="`${item.nickName}（${item.userName}）`"
              :value="item.userId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属组别" prop="channelGroup">
          <treeselect v-model="form.channelGroup"
                      :defaultExpandLevel="5"
                      :searchable="true"
                      :options="deptOptions" :show-count="true" placeholder="请选择归属部门" />
        </el-form-item>
        <el-form-item label="人员列表" prop="channelUserIds">
          <el-select v-model="channelUserIds" multiple filterable placeholder="请选择系统下属人员">
            <el-option
              v-for="item in userList"
              :key="item.userId"
              :label="`${item.nickName}（${item.userName}）`"
              :value="item.userId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="channelRemark">
          <el-input type="textarea" v-model="form.channelRemark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 系统导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的应用系统数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listChannel, getChannel, delChannel, addChannel, updateChannel, listUser} from "@/api/yjcz/channel";
import Treeselect from "@riophae/vue-treeselect";
import {deptTreeSelect} from "@/api/system/user";

import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {getToken} from "@/utils/auth";

export default {
  name: "Channel",
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      channelCodes: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 应用系统表格数据
      channelList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        channelName: null,
        channelCode: null,
        channelGroup: null,
      },
      // 表单参数
      form: {},
      channelUserIds: [],
      userList: [],
      deptOptions: null,
      // 表单校验
      rules: {
        channelName: [
          { required: true, message: '请输入应用系统名称', trigger: 'blur' },
          { min: 3, max: 50, message: '长度在 3 到 50 个字符', trigger: 'blur' }
        ],
        channelCode: [
          { required: true, message: '请输入应用系统编号', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        // channelUserId: [
        //   { required: true, message: '请选择系统负责人', trigger: 'change' }
        // ],
        channelGroup: [
          { required: true, message: '请选择所属组别', trigger: 'change' }
        ]
      },
      // 系统导入参数
      upload: {
        // 是否显示弹出层（系统导入）
        open: false,
        // 弹出层标题（系统导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的系统数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/yjcz/channel/importData"
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询应用系统列表 */
    getList() {
      this.loading = true;
      listChannel(this.queryParams).then(response => {
        this.channelList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.channelUserIds = []
      this.form = {
        pkId: null,
        channelName: null,
        channelCode: null,
        channelUserId: null,
        channelGroup: null,
        channelGroupName: null,
        channelRemark: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.pkId)
      this.channelCodes = selection.map(item => item.channelCode)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getUserList();
      this.getDeptTree();
      this.open = true;
      this.title = "添加应用系统";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getUserList();
      this.getDeptTree();
      const pkId = row.pkId || this.ids
      getChannel(pkId).then(response => {
        this.form = response.data;
        let channelUserIds = this.form.channelUserIds
        if (channelUserIds) {
          let arr = channelUserIds.split(',')
          for (let i = 0; i < arr.length; ++ i) {
            this.channelUserIds.push(Number(arr[i]))
          }
        }
        this.open = true;
        this.title = "修改应用系统";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.channelUserIds = this.channelUserIds.join(',')
          if (this.form.pkId != null) {
            updateChannel(this.form).then(response => {
              if (response.code !== 200) {
                this.$modal.msgError(response.msg)
                return
              }
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addChannel(this.form).then(response => {
              if (response.code !== 200) {
                this.$modal.msgError(response.msg)
                return
              }
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const pkIds = row.pkId || this.ids;
      const codes = row.channelCode || this.channelCodes
      this.$modal.confirm('是否确认删除应用系统编号为"' + codes + '"的数据项？').then(function() {
        return delChannel(pkIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "应用系统导入";
      this.upload.open = true;
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('yjcz/channel/export', {
        ...this.queryParams
      }, `channel_${new Date().getTime()}.xlsx`)
    },
    /** 查询用户列表 */
    getUserList () {
      listUser().then(response => {
        if (response.code === 200) {
          this.userList = response.data
        }
      })
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
      });
    },
    /** 当选择的系统负责人发生变化时 */
    onUserListChange () {
      if (this.form.channelUserId) {
        const userInfo = this.userList.filter(u => u.userId === this.form.channelUserId)[0]
        const dept = userInfo.dept
        this.form.channelGroupName = dept.deptName
        this.form.channelGroup = dept.deptId
        return
      }
      this.form.channelGroupName = ''
      this.form.channelGroup = ''
    },

    /** 下载模板操作 */
    importTemplate() {
      this.download('yjcz/channel/importTemplate', {
      }, `channel_template_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      if (response.code !== 200) {
        return
      }
      this.upload.open = false;
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  }
};
</script>
<style>
.my-tooltip {
  max-width: 300px;
}
</style>
